package com.yuan.fruitweb.util;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author YuanYuemeng
 * @date 2020/11/19
 */
public class JdbcUtil {
    private static final Properties JDBC_PROPERTIES = new Properties();
    //文件只需要读取一次
    static{

        try {
            JDBC_PROPERTIES.load(JdbcUtil.class.getResourceAsStream("jdbc.properties"));
        }catch (IOException e){
            e.printStackTrace();
        }
        try{
            Class.forName(JDBC_PROPERTIES.getProperty("jdbc.driverClassName"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws SQLException {
        String url = JDBC_PROPERTIES.getProperty("jdbc.url");
        String username = JDBC_PROPERTIES.getProperty("jdbc.username");
        String password = JDBC_PROPERTIES.getProperty("jdbc.password");
        return DriverManager.getConnection(url, username, password);
    }
    public static void free(Statement stmt,Connection connection){
        if (stmt!=null){
            try{
                stmt.close();
            }catch (SQLException exception){
                exception.printStackTrace();
            }
        }
        if (connection!=null){
            try{
                connection.close();
            }catch (SQLException throwables){
                throwables.printStackTrace();
            }
        }
    }
    public static void free(ResultSet rs,Statement stmt,Connection connection){
        if (rs!=null){
            try {
                rs.close();
            }catch (SQLException exception){
                exception.printStackTrace();
            }
        }
        free(stmt,connection);
    }
}
